package password.hb.com.password.util;

import android.content.Context;
import android.os.Environment;
import android.util.Log;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * Created by A on 2017/1/17.
 */

public class WriteFile {

    private File file;
    private FileWriter fileWriter;
    private BufferedWriter bw;
    private String path;

    private String fileName;

    public WriteFile(String path,String fileName){
        init(path,fileName);
    }

    //默认为Android根目录
    public WriteFile(String fileName){
        String path = Environment.getExternalStorageDirectory().getPath();
        Log.d("路径",path);
        init(path,fileName);
    }

    private void init(String path,String fileName){
        this.fileName = fileName;
        this.path = path+"/"+fileName;
        try{
            this.file = new File(this.path);
            this.fileWriter = new FileWriter(file,false);
            this.bw = new BufferedWriter(fileWriter);
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public String getPath(){
        return this.path;
    }

    public void write(String content){
        try{
            bw.write(content);
            bw.write("\n");
            bw.write("----------------------------------------");
            bw.write("\n");
        }catch(Exception e){
            e.printStackTrace();
        }
    }


    public void writeClose(){
        try{
            bw.flush();
            bw.close();
            this.fileWriter.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
